<template>
  <div class="page-store-select">
    <div class="baseDiv">
      <div style="width: 50%">
        <div style="margin-bottom: 10px;">省份</div>
        <el-select style="width: 420px" v-model.number="expectProv" value-key="id" clearable placeholder="请选择省份"
                   @change="handleProvinceChange">
          <el-option
            v-for="item in provinces"
            :key="item.id"
            :label="item.nodeName"
            :value="item">
            <span style="float: left">{{ item.nodeName }}</span>
          </el-option>
        </el-select>
      </div>
      <div style="width: 50%; text-align: right">
        <div style="margin-left: 38px; margin-bottom: 10px; text-align: left;">城市</div>
        <el-select style="width: 420px" v-model="expectCities" value-key="id" clearable multiple collapse-tags
                   placeholder="请选择城市" @change="handleCityChange">
          <el-option
            v-for="item in cities"
            :key="item.id"
            :label="item.nodeName"
            :value="item">
            <span style="float: left">{{ item.nodeName }}</span>
          </el-option>
        </el-select>
      </div>

    </div>
    <egrid class="egrid-class" border
           column-type="selection"
           ref="multipleTable"
           :header-cell-style="getHeaderCellClass"
           :data="storageList"
           :columns="columns"
           :columns-schema="columnsSchema"
           :columns-props="columnsProps"
           @select="handleSelect"
           @selection-change="selectionChange">
    </egrid>

    <el-button class="singleBtnClass" type="primary" @click="confirm()">确定</el-button>
    <pc-dialog :is-show="showDetailDialog" title="查看详情" @on-close="showDetailDialog = false">
      <store-detail :storageId="storageId"></store-detail>
    </pc-dialog>
  </div>
</template>
<script type="text/ecmascript-6">
  import PcDialog from 'components/dialog';
  import LongContentCol from 'components/wms/comm/LongContentColComponent';
  import EgridCellView from 'components/wms/comm/EgridCellView';
  import StoreDetail from '@/views/wms/storemanage/storeDetail';
  import mValidate from 'utils/common-method/validate/index';
  import {validateTips} from 'utils/tips';
  let that;
  // 操作按钮
  var Btn = {
    template: `<div style="display:flex; width: 100%;flex-wrap: wrap">
        <el-button type="primary" plain @click="viewdetail(row)">查看详情</el-button>
      </div>`,
    props: ['row'],
    computed: {},
    methods: {
      viewdetail(val) {
        this.$emit('show-detail', val);
      }
    }
  };
  export default {
    props: {
      roleType: {
        type: Number
      },
      params: Object
    },
    components: {
      PcDialog, StoreDetail, EgridCellView
    },
    data() {
      return {
        storageId: null,
        storageList: [],
        provinceId: this.params.provinceId,
        cityIds: this.params.cityIds,
        provinces: [],
        cities: [],
        expectProv: this.params.provinceName,
        expectCities: this.params.city,
        columns: [
          /* {
            label: '',
            width: 40,
            component: RadioButton, // 'el-button'
            listeners: {
              'select-row' (data) {
                that.selectStorage = data;
              }
            },
            propsHandler: function ({ row, col, column }) {
              return {row, col, column};
            }
          }, */
          {
            label: '冷库名称',
            prop: 'storageName'
          },
          {
            label: '所在城市',
            prop: 'cityName'
          },
          {
            label: '建筑面积（㎡）',
            prop: 'conArea'
          },
          {
            label: '仓储功能',
            prop: 'storageFun'
          },
          {
            label: '参考价格（元/m² • 天）',
            prop: 'referencePrice'
          },
          {
            label: '库容（万吨）',
            prop: 'storageCapacity'
          }, {
            label: '联系电话',
            prop: 'applicantConTel'
          },
          {
            label: '操作',
            width: 116,
            component: Btn, // 'el-button'
            listeners: {
              'show-detail' (data) {
                that.showDetail(data);
              }
            },
            propsHandler: function ({ row, col, column }) {
              return {row, col, column};
            }
          }
        ],
        columnsSchema: {
          '冷库名称': {
            minWidth: 200,
            component: LongContentCol // 列内容过长内容展示组件（设置超出部分隐藏，鼠标移上去显示全部）
          },
          '所在城市': { minWidth: 100 },
          '参考价格（元/m² • 天）': { minWidth: 200 },
          '操作': { fixed: 'right' }
        },
        // columnsProps 用于定义所有 columns 公共的属性，
        // 这里属性可以参考这里： http://element.eleme.io/#/zh-CN/component/table#table-column-attributes
        columnsProps: {
          height: 40,
          minWidth: 150,
          align: 'center',
          showOverflowTooltip: true,
          component: EgridCellView
        },
        selectStorage: {},
        showDetailDialog: false
      };
    },
    created () {
      that = this;
      this.provinces = this.$pcLockr.get(this.$pcEnum.ADDRESS.DISTRICT); // 从浏览器中读取缓存的城市数据
      // 去除掉多余三级城市的数据
      this.provinces.forEach(function(province, index) {
        if (province.children) {
          province.children.forEach(function(child, index) {
            if (child.children) {
              child.children = null;
            }
          });
        }
      });
      this.cities = mValidate.stringIsNullOrEmpty(this.provinceId) ? [] : this.getCities(this.provinceId);
      // 查询仓库数据
      this.queryStoreage();
    },
    methods: {
      // 根据城市ID查询仓库数据
      queryStoreage() {
        this.ajax({
          type: 'POST',
          url: '/maliwms/storage/selectStorage',
          data: {provinceId: this.provinceId, cityIds: this.cityIds},
          loading: true,
          success: (res) => {
            setTimeout(() => {
              this.$pcNProgress.done();
            }, 300);
            this.storageList = res.result;
          }
        });
      },
      // 根据服务端返回的省市ID获取下一级城市数据
      getCities(provinceId) {
        let cities = [];
        this.provinces.forEach(function (item, index) {
          if (item.id === provinceId) {
            cities = item.children;
          }
        });
        return cities;
      },
      // 选择省份变化是回调函数
      handleProvinceChange(val) {
//        console.log('handleProvinceChange: ' + JSON.stringify(val));
        this.cities = val.children;
        this.expectCities = [];
        this.provinceId = val.id;
      },
      // 选择城市变化是回调函数
      handleCityChange(val) {
//        console.log('handleCityChange: ' + JSON.stringify(val));
        this.cityIds = [];
        let that = this;
        // 循环取出选择的城市数据，获取城市的id和名字
        val.forEach(function(city, index) {
          if (city) {
            that.cityIds.push(city.id);
          }
        });
        // 判断选择的城市数组是否empty，如果是则设置为null
        if (this.cityIds.length === 0) {
          this.cityIds = null;
        }
        this.queryStoreage();
      },
      handleSelect(selection, row) {
        this.$refs.multipleTable.clearSelection();
        if (row) {
          this.$refs.multipleTable.toggleRowSelection(row);
        }
      },
      /*
       选中内容变化时触发的回调函数
       rows 选中行的数据
       */
      selectionChange(row) {
        this.selectStorage = row;
        this.$emit('selection-change', row);
      },
      // 确定选择仓库，返回一个页面
      confirm() {
        let arr = Object.keys(this.selectStorage); // 获取对象的字段数组
        if (this.selectStorage && arr.length > 0) {
          this.$emit('selected', this.selectStorage);
        } else {
          this.errorTip(validateTips.SELECT_STORAGE);
        }
//        this.showDetailDialog = true;
      },
      showDetail(val) {
        this.showDetailDialog = true;
        this.storageId = val.id;
//        console.log('showDetail------val: ' + JSON.stringify(val));
      },
      // 定义表头的样式
      getHeaderCellClass({ row, column, rowIndex, columnIndex }) {
        if (rowIndex === 0 && columnIndex === 0) {
          return 'background: #ffffff; height: 50px;';
        } else if (rowIndex === 0) {
          return 'background: #ffffff; height: 50px;';
        } else {
          return '';
        }
      }
    }
  };
</script>
<style>
  .page-store-select {
    position: relative;
  }
  .page-store-select .el-table--border th:first-child .cell{
    display: none;
  }
  .page-store-select .baseDiv {
    display: flex;
    flex-wrap: wrap;
    width: 958px;
    height: auto;
    border: 1px solid #e5e5e5;
    background-color: white;
    padding: 24px 20px;
  }

  .page-store-select .egrid-class {
    margin-top: 20px;
    margin-bottom: 40px;
  }
  .page-store-select .singleBtnClass {
    position: absolute;
    left: 0;
    right: 0;
    margin: 0 auto;
    text-align: center;
  }
</style>
